LeetCode JS Easy 2704. To Be Or Not To Be


Posted by Lucy on 2023-06-10

這是30 Days of JavaScript中的題型
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.

toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal".
notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal".
最常見寫法應該就兩個function

var expect = function(val) {
    const toBe=(eqalVal)=>{if(val===eqalVal)return true
                throw new Error("Not Equal")
    }    
    const notToBe=(eqalVal)=>{if(val!==eqalVal)return true
                throw new Error("Equal")
    }
      return {
          toBe:toBe,
          notToBe:notToBe,
      }
};

不過不知道為什麼我就很想寫共用function,下面這段是第一次寫的

var expect = function(val) {
    const fn=(eqalVal,isToBe)=>{
            const isEqal=val===eqalVal
            if(isToBe){
                if(isEqal)return true
                throw new Error("Not Equal")
            }else{
                if(isEqal)throw new Error("Equal")
                return true
            }
        }
      return {
          toBe:(eqalVal)=>fn(eqalVal,true),
          notToBe:(eqalVal)=>fn(eqalVal,false),
      }
};

#leetcode Js







Related Posts

不要問我從哪裡來 - noopener & noreferrer & nofollow

不要問我從哪裡來 - noopener & noreferrer & nofollow

N4.1_Webpack 是什麼及為什麼要用它?

N4.1_Webpack 是什麼及為什麼要用它?

如何阻擋android原生的statusBar

如何阻擋android原生的statusBar


Comments